package com.book.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.book.domain.User;
import com.book.util.DBUtil;

public class UserDao {

	/**
	 * 列出所有用户返回所有用户集合
	 * @return
	 */
	public List<User> listAllUsers(){
		PreparedStatement preparedStatement=null;
		ResultSet resultSet=null;
		List<User> userslist=new ArrayList<User>();
	    Connection connection=	DBUtil.getConnection();
	String sql="select * from t_user";
	try {
		preparedStatement=	connection.prepareStatement(sql);
		resultSet=preparedStatement.executeQuery();
		while (resultSet.next()) {
			User user=new User(resultSet.getInt("id"), resultSet.getString("username"), resultSet.getString("password"));
			userslist.add(user);
			
			
		}
		
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally{
		
		DBUtil.closeConnection(preparedStatement, resultSet, connection);
	}
		return userslist;
	}
	/**
	 * 修改用户
	 * 
	 */
	public void updateUser(User user){
		PreparedStatement preparedStatement=null;
		ResultSet resultSet=null;
		
	    Connection connection=	DBUtil.getConnection();
	    String sql="update t_user set username=?,password=? where id=?";
		
		try {
			connection.prepareStatement(sql);
			preparedStatement.setInt(3, user.getId());
			preparedStatement.setString(1, user.getUsername());
			preparedStatement.setString(2, user.getPassword());
			preparedStatement.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
     /**
      * 
      * @return
      */
	public List<User> selectUsers(User user){
		PreparedStatement preparedStatement=null;
		ResultSet resultSet=null;
		List<User> userslist=new ArrayList<User>();
	    Connection connection=	DBUtil.getConnection();
	   String sql="select * from t_user where id=?";
	try {
		preparedStatement=	connection.prepareStatement(sql);
		preparedStatement.setInt(1, user.getId());
		resultSet=preparedStatement.executeQuery();
		while (resultSet.next()) {
			User user1=new User(resultSet.getInt("id"), resultSet.getString("username"), resultSet.getString("password"));
			userslist.add(user1);
			System.out.println(user1);
			
		}
		
	} catch (SQLException e) {
		e.printStackTrace();
	}finally{
		
		DBUtil.closeConnection(preparedStatement, resultSet, connection);
	}
		return userslist;
	}
	
}
